package com.bupt.Factory;

import com.bupt.annotation.MParam;
import com.bupt.basic.Project;
import com.bupt.exception.BaseException;

import java.io.*;

public class ProjectFactory {
    //项目存储路径
    //服务器存储地址

    public static final String storePath="/root/Demo/projects/";

    //本机测试地址
//public static final String storePath="D:\\TestProject\\";



    //存储项目到文件中
    public static boolean saveObjectDataToFile(@MParam("项目数据") Project project,
                                           @MParam("数据标识ID") String dataId,
                                           @MParam("存储路径") String path) throws BaseException {


        File file = new File(path,dataId+".project");
        if (file.exists()) {
            boolean res = file.delete();
            // 删除存在的文件
        }
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(project);
            return true;
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        } finally {
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    throw new BaseException("文件操作异常");
                }
            }
        }
    }

    //从文件中读取project
    public static Project getObjectFromFile(@MParam("数据的ID") String dataId,
                                            @MParam("文件的存储路径") String path) throws BaseException {
        if (null == dataId || "".equals(dataId)) {
            return null;
        }
        // 文件夹
        File director = new File(path);
        if (!director.exists()) {
            return null;
        }
        // 获取文件的名字
        File file = new File(path,dataId+".project");
        if (!file.exists()) {
            return null;
        }
        ObjectInputStream ios = null;
        try {
            ios = new ObjectInputStream(new FileInputStream(file));
            return (Project) ios.readObject();
        } catch (Exception e) {
            // throw
            throw new BaseException("获取对象失败");

        } finally {
            if (null != ios) {
                try {
                    ios.close();
                } catch (IOException e) {
                    throw new BaseException("操作文件异常");
                }
            }
        }
    }
}
